package com.xq.hibernate;

import com.xq.hibernate.entity.Event;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.Date;
import java.util.List;

/**
 * 功能说明: 第一个JPA测试类.
 * <p>创建时间: 2018-10-17 19:05</p>
 *
 * @author 郭凯强
 * @version 1.0-SNAPSHOT
 */
public class JpaTest01 extends BaseJpaTest {
    public void testBaseUsage() {
        // create a couple of events...
        EntityManager entityManager = getEntityManagerFactory().createEntityManager();
        // 使用EntityTransaction
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        entityManager.persist(new Event("Our very first event!", new Date()));
        entityManager.persist(new Event("A follow up event", new Date()));
        transaction.commit();
        entityManager.close();

        // now lets pull events from the database and list them
        entityManager = getEntityManagerFactory().createEntityManager();
        transaction = entityManager.getTransaction();
        transaction.begin();
        List<Event> result = entityManager.createQuery("from Event", Event.class).getResultList();
        result.forEach(event -> System.out.println(event));
        transaction.commit();
        entityManager.close();
    }
}
